package com.suneast.suneaststore.modules.personal.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suneast.suneaststore.API;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.bean.personal.order.DetailBean;
import com.suneast.suneaststore.bean.personal.order.ExpressCompanyBean;
import com.suneast.suneaststore.bean.personal.order.FastOrderDetailBean;
import com.suneast.suneaststore.bean.personal.order.ListBean;
import com.suneast.suneaststore.modules.common.CommonUtil;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.personal.order.event.CancelResult;
import com.suneast.suneaststore.modules.personal.order.event.ConfirmDeliverGoodsResult;
import com.suneast.suneaststore.modules.personal.order.event.ConfirmReceivedGoodsResult;
import com.suneast.suneaststore.modules.personal.order.event.CustomizeResult;
import com.suneast.suneaststore.modules.personal.order.event.DeleteResult;
import com.suneast.suneaststore.modules.personal.order.event.DetailResult;
import com.suneast.suneaststore.modules.personal.order.event.ExpressListResult;
import com.suneast.suneaststore.modules.personal.order.event.FastOrderSetResult;
import com.suneast.suneaststore.modules.personal.order.event.GotFastOrderResult;
import com.suneast.suneaststore.modules.personal.order.event.ListResult;
import com.suneast.suneaststore.util.log.LatteLogger;
import com.suneast.suneaststore.util.net.RestClient;

import org.greenrobot.eventbus.EventBus;

public class OrderHandler {
    private final static int[] ORDER_TYPES = new int[]{
            0, // REQ_ALL
            1,  // REQ_UNPAID
            2,  // REQ_TOBE_DELIVERED
            3,  // REQ_TOBE_RECEIVED
            4,  // REQ_TOBE_COMMENTED REQ_FINISHED
            5   // REQ_AFTER_SALES
    };

    public final static int ORDER_CANCELED = 0;        // 已取消
    public final static int ORDER_UNPAID = 1;          // 待付款
    public final static int ORDER_TOBE_DELIVERED = 2;  // 待发货
    public final static int ORDER_TOBE_RECEIVED = 3;   // 待收货
    public final static int ORDER_TOBE_COMMENTED = 4;  // 待评价（已完成）
    public final static int ORDER_AFTER_SALES = 5;     // 售后（退/换货）

    public static void requestPurchaseList(int orderChoice, int page) {
        LatteLogger.d("debug", "orderChoice: " + orderChoice + " page: " + page);
        RestClient.builder()
                .url(API.USER_ORDER_LIST2)
                .params("token", AccountManager.getToken())
                .params("type", ORDER_TYPES[orderChoice])
                .params("page", page)
                .params("psize", 12) // 默认一次请求最多12条
                .success((response) -> {
                    LatteLogger.json(API.USER_ORDER_LIST2, response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new ListResult(Flag.Result.SUCCEED, orderChoice,
                                JSON.parseObject(rootJObj.getJSONObject("data").toJSONString(), ListBean.class)));
                    } else {
                        EventBus.getDefault().post(new ListResult(Flag.Result.FAILURE, orderChoice, rootJObj.getString("msg")));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "requestPurchaseList failure");
                    EventBus.getDefault().post(new ListResult(Flag.Result.FAILURE, orderChoice, "请求失败"));
                    LatteLogger.e("error", "requestListByStatus2 failure");
                    EventBus.getDefault().post(new ListResult(Flag.Result.FAILURE, orderChoice, "请求失败"));
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestPurchaseList error code = "
                            + code + " msg = " + msg);
                    EventBus.getDefault().post(new ListResult(Flag.Result.FAILURE, orderChoice, "code = " + code + " msg = " + msg));
                })
                .build()
                .post();
    }

    public static void requestSaleList(int type, int page) {
        LatteLogger.d("debug", "order type: " + type + " page: " + page);
        RestClient.builder()
                .url(API.MERCH_ORDER_LIST)
                .params("token", AccountManager.getToken())
                .params("type", ORDER_TYPES[type])
                .params("page", page)
                .params("psize", 12) // 默认一次请求最多12条
                .success((response) -> {
                    LatteLogger.json(API.MERCH_ORDER_LIST, response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new ListResult(Flag.Result.SUCCEED, type,
                                JSON.parseObject(rootJObj.getJSONObject("data").toJSONString(), ListBean.class)));
                    } else {
                        EventBus.getDefault().post(new ListResult(Flag.Result.FAILURE, type, rootJObj.getString("msg")));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "requestSaleList failure");
                    EventBus.getDefault().post(new ListResult(Flag.Result.FAILURE, type, "请求失败"));
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestSaleList error code = "
                            + code + " msg = " + msg);
                    EventBus.getDefault().post(new ListResult(Flag.Result.FAILURE, type, "code = " + code + " msg = " + msg));
                })
                .build()
                .post();
    }

    public static void requestOrderDetail(int id) {
        RestClient.builder()
                .url(API.GET_BILL_DETAIL)
                .params("token", AccountManager.getToken())
                .params("id", id)
                .success((response) -> {
                    LatteLogger.json(API.GET_BILL_DETAIL, response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new DetailResult(Flag.Result.SUCCEED,
                                JSON.parseObject(rootJObj.getJSONObject("data").toJSONString(), DetailBean.class)));
                    } else {
                        EventBus.getDefault().post(new DetailResult(Flag.Result.FAILURE, rootJObj.getString("msg")));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "requestOrderDetail failure");
                    EventBus.getDefault().post(new DetailResult(Flag.Result.FAILURE, "请求失败"));
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestOrderDetail error code = "
                            + code + " msg = " + msg);
                    EventBus.getDefault().post(new DetailResult(Flag.Result.FAILURE, "code = " + code + " msg = " + msg));
                })
                .build()
                .post();
    }


    public static void submitFastOrder(String demand, int addressid, int merchid, String imgs) {
        RestClient.builder()
                .url(API.BATCH_ORDER)
                .params("token", AccountManager.getToken())
                .params("demand", demand)
                .params("addressid", addressid)
                .params("merchid", merchid)
                .params("imgs", imgs)
                .success((response) -> {
                    LatteLogger.json(API.BATCH_ORDER, response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new CustomizeResult(Flag.Result.SUCCEED, rootJObj.getJSONObject("data").getString("ordersn"), null));
                    } else {
                        EventBus.getDefault().post(new CustomizeResult(Flag.Result.FAILURE, rootJObj.getString("msg")));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", API.BATCH_ORDER + " failure");
                    EventBus.getDefault().post(new CustomizeResult(Flag.Result.FAILURE, "请求失败"));
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", API.BATCH_ORDER + " error code = "
                            + code + " msg = " + msg);
                    EventBus.getDefault().post(new CustomizeResult(Flag.Result.FAILURE, "code = " + code + " msg = " + msg));
                })
                .build()
                .post();
    }

    public static void cancelOrder(int id, String remark, int pos) {
        RestClient.builder()
                .url(API.CANCEL_ORDER)
                .params("token", AccountManager.getToken())
                .params("id", id)
                .params("remark", remark)
                .success((response) -> {
                    LatteLogger.json(API.CANCEL_ORDER, response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new CancelResult(Flag.Result.SUCCEED, pos));
                    } else {
                        EventBus.getDefault().post(new CancelResult(Flag.Result.FAILURE, rootJObj.getString("msg")));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", API.CANCEL_ORDER + " failure");
                    EventBus.getDefault().post(new CancelResult(Flag.Result.FAILURE, "请求失败"));
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", API.CANCEL_ORDER + " error code = "
                            + code + " msg = " + msg);
                    EventBus.getDefault().post(new CancelResult(Flag.Result.FAILURE, "code = " + code + " msg = " + msg));
                })
                .build()
                .post();
    }

    public static void deleteOrder(int id, int pos) {
        RestClient.builder()
                .url(API.DELETE_ORDER)
                .params("token", AccountManager.getToken())
                .params("id", id)
                .success((response) -> {
                    LatteLogger.json(API.DELETE_ORDER, response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new DeleteResult(Flag.Result.SUCCEED, pos));
                    } else {
                        EventBus.getDefault().post(new DeleteResult(Flag.Result.FAILURE, rootJObj.getString("msg")));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", API.DELETE_ORDER + " failure");
                    EventBus.getDefault().post(new DeleteResult(Flag.Result.FAILURE, "请求失败"));
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", API.DELETE_ORDER + " error code = "
                            + code + " msg = " + msg);
                    EventBus.getDefault().post(new DeleteResult(Flag.Result.FAILURE, "code = " + code + " msg = " + msg));
                })
                .build()
                .post();
    }

    public static void confirmReceivedGoods(int id, int pos) {
        RestClient.builder()
                .url(API.CONFIRM_RECEIVED_GOODS)
                .params("token", AccountManager.getToken())
                .params("id", id)
                .success((response) -> {
                    LatteLogger.json(API.DELETE_ORDER, response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new ConfirmReceivedGoodsResult(Flag.Result.SUCCEED, pos));
                    } else {
                        EventBus.getDefault().post(new ConfirmReceivedGoodsResult(Flag.Result.FAILURE, rootJObj.getString("msg")));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", API.CONFIRM_RECEIVED_GOODS + " failure");
                    EventBus.getDefault().post(new ConfirmReceivedGoodsResult(Flag.Result.FAILURE, "请求失败"));
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", API.CONFIRM_RECEIVED_GOODS + " error code = "
                            + code + " msg = " + msg);
                    EventBus.getDefault().post(new ConfirmReceivedGoodsResult(Flag.Result.FAILURE, "code = " + code + " msg = " + msg));
                })
                .build()
                .post();
    }

    public static void requestFastOrderDetail(int id) {
        RestClient.builder()
                .url(API.GET_FAST_ORDER_DETAIL)
                .params("token", AccountManager.getToken())
                .params("orderid", id)
                .success((response) -> {
                    LatteLogger.json(API.DELETE_ORDER, response);
                    JSONObject dataObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataObj != null) {
                        EventBus.getDefault().post(new GotFastOrderResult(JSON.parseObject(
                                dataObj.toJSONString(), FastOrderDetailBean.class), Flag.Result.SUCCEED));
                    }
                })
                .failure(() -> {
                    EventBus.getDefault().post(new GotFastOrderResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", API.GET_FAST_ORDER_DETAIL + " failure");
                })
                .error((int code, String msg) -> {
                    EventBus.getDefault().post(new GotFastOrderResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", API.GET_FAST_ORDER_DETAIL + " error code = "
                            + code + " msg = " + msg);
                })
                .build()
                .post();

    }

    public static void setFastOrder(int orderId, double price, String urlListStr, String textListStr) {
        RestClient.builder()
                .url(API.SET_FAST_ORDER_DETAIL)
                .params("token", AccountManager.getToken())
                .params("orderid", orderId)
                .params("price", price)
                .params("explainImg", urlListStr)
                .params("explainText", textListStr)
                .success((response) -> {
                    LatteLogger.json(API.DELETE_ORDER, response);
                    JSONObject rootObj = JSON.parseObject(response);
                    if (rootObj != null && rootObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new FastOrderSetResult(Flag.Result.SUCCEED));
                    } else {
                        EventBus.getDefault().post(new FastOrderSetResult(Flag.Result.FAILURE));
                    }
                })
                .failure(() -> {
                    EventBus.getDefault().post(new FastOrderSetResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", API.SET_FAST_ORDER_DETAIL + " failure");
                })
                .error((int code, String msg) -> {
                    EventBus.getDefault().post(new FastOrderSetResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", API.SET_FAST_ORDER_DETAIL + " error code = "
                            + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    public static void requestExpressCompanyList() {
        RestClient.builder()
                .url(API.GET_EXPRESS_LIST)
                .success((response) -> {
                    LatteLogger.json(API.DELETE_ORDER, response);
                    JSONObject rootObj = JSON.parseObject(response);
                    if (rootObj != null && rootObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new ExpressListResult(Flag.Result.SUCCEED,
                                JSON.parseArray(rootObj.getJSONArray("data").toJSONString(),
                                        ExpressCompanyBean.class)));
                    } else {
                        EventBus.getDefault().post(new ExpressListResult(Flag.Result.FAILURE, "数据错误"));
                    }
                })
                .failure(() -> {
                    EventBus.getDefault().post(new ExpressListResult(Flag.Result.FAILURE, "数据错误"));
                    LatteLogger.e("error", API.GET_EXPRESS_LIST + " failure");
                })
                .error((int code, String msg) -> {
                    EventBus.getDefault().post(new ExpressListResult(Flag.Result.FAILURE, msg));
                    LatteLogger.e("error", API.GET_EXPRESS_LIST + " error code = "
                            + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    public static void confirmDeliverGoods(int pos, int orderId, String company, String express, String expresssn) {
        RestClient.builder()
                .url(API.CONFIRM_DELIVER_GOODS)
                .params("token", AccountManager.getToken())
                .params("orderid", orderId)
                .params("expresscom", company)
                .params("express", express)
                .params("expresssn", expresssn)
                .success((String response) -> {
                    LatteLogger.json("test", response);
                    JSONObject rootObj = JSON.parseObject(response);
                    if (rootObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(
                                new ConfirmDeliverGoodsResult(Flag.Result.SUCCEED, pos));
                    } else {
                        LatteLogger.e("error", "confirmDeliverGoods() failure");
                        EventBus.getDefault().post(
                                new ConfirmDeliverGoodsResult(Flag.Result.FAILURE, pos));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "confirmDeliverGoods() failure");
                    EventBus.getDefault().post(
                            new ConfirmDeliverGoodsResult(Flag.Result.FAILURE, pos));
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "confirmDeliverGoods() error code = "
                            + code + " msg = " + msg);
                    EventBus.getDefault().post(
                            new ConfirmDeliverGoodsResult(Flag.Result.FAILURE, pos));
                })
                .build()
                .post();
    }
}
